package com.bskj.sj.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.bskj.common.bean.model.BmsUser;
import com.bskj.common.bean.model.ParkingLotCustomer;
import com.bskj.common.bean.model.ShopCoupon;
import com.bskj.common.bean.model.ShortUrl;
import com.bskj.common.bean.model.UserCoupon;
import com.bskj.common.constants.CommonConstatns;
import com.bskj.common.dao.core.FindRequestEntity;
import com.bskj.common.dao.core.WhereEnum;
import com.bskj.common.enums.BmsUserTypeEnum;
import com.bskj.common.utils.DateTimeUtil;
import com.bskj.common.utils.EncryptUtil;
import com.bskj.common.utils.Global;
import com.bskj.common.utils.HttpRequestUtil;
import com.bskj.common.utils.LogUtils;
import com.bskj.common.utils.QrCodeCreateUtil;
import com.bskj.common.utils.ResultMapUtil;
import com.bskj.common.utils.ShortUrlUtil;
import com.bskj.common.utils.StringUtils;
import com.bskj.common.web.BaseController;
import com.bskj.sj.bean.vo.resp.ShopCouponVo;
import com.bskj.sj.bean.vo.resp.UserCouponRecordRespVo;
import com.bskj.sj.bean.vo.resp.UserCouponReleaseRespVo;
import com.bskj.sj.service.IBmsUserService;
import com.bskj.sj.service.IParkingLotCustomerService;
import com.bskj.sj.service.IParkingShopService;
import com.bskj.sj.service.IShopCouponService;
import com.bskj.sj.service.IShortUrlService;

/**
 * Created by mocaijin on 20/01/2018.
 */
@Controller
@RequestMapping("/coupon")
public class ShopCouponController extends BaseController {

	@Autowired
	private IShopCouponService shopCouponService;

	@Autowired
	private IParkingLotCustomerService parkingLotCustomerService;

	@Autowired
	private IShortUrlService shortUrlService;

	@Autowired
	private IBmsUserService bmsUserService;

	@Autowired
	private IParkingShopService parkingShopService;

	/**
	 * 发放停车券
	 *
	 * @param
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("page/releaseCouponIndex")
	public ModelAndView releaseCouponsIndex(Integer custId, Integer shopId) throws Exception {
		LogUtils.debug(JSONObject.toJSONString(getRequest().getParameterMap()));
		ModelAndView mv = new ModelAndView();
		mv.setViewName("/coupon/releaseCoupon");
		ShopCoupon shopCoupon = new ShopCoupon();
		if (custId != null) {
			shopCoupon.setParkingLotCustomerId(custId);
		}
		shopCoupon.setShopId(shopId);
		List<ShopCoupon> shopCoupons = shopCouponService.getShopCoupons(shopCoupon, 0,
				CommonConstatns.DEFAULT_PAGE_SZIE);
		List<ShopCouponVo> shopCouponVos = new ArrayList<>();
		for (ShopCoupon item : shopCoupons) {
			JSONObject generalQRCodeParams = new JSONObject();
			generalQRCodeParams.put("uri", "/coupon/generalQRCode");
			generalQRCodeParams.put("custId", custId);
			generalQRCodeParams.put("shopId", shopId);

			UserCoupon userCoupon = new UserCoupon();
			userCoupon.setParkingLotCustomerId(item.getParkingLotCustomerId());
			userCoupon.setCouponMoneyType(item.getCouponMoneyType());
			userCoupon.setMoney(item.getMoney());
			userCoupon.setValidType(item.getValidType());
			userCoupon.setShopId(shopId);
			userCoupon.setStatus(0);
			userCoupon.setCouponId(item.getId());
			userCoupon.setLimitModeType(item.getLimitModeType());

			generalQRCodeParams.put("userCouponEncryptStr", userCoupon.toEncryptJSONString());
			String encryptParams = EncryptUtil.encrypt(generalQRCodeParams.toJSONString());
			item.setEncryptParams(encryptParams);

			ShopCouponVo shopCouponVo = new ShopCouponVo();
			shopCouponVo = shopCouponVo.getShopCouponVo(item);

			shopCouponVos.add(shopCouponVo);
		}
		mv.addObject("shopCouponVos", shopCouponVos);
		FindRequestEntity findReq = new FindRequestEntity();
		findReq.addWhere("shop_id", WhereEnum.EQ, shopId);
		List<BmsUser> bmsUsers = bmsUserService.find(findReq);
		JSONObject releaseCouponListParams = new JSONObject();
		releaseCouponListParams.put("uri", "/coupon/page/parkingLotCouponsIndex");
		releaseCouponListParams.put("custId", custId);
		releaseCouponListParams.put("authId", bmsUsers.get(0).getId());
		mv.addObject("parkingLotCouponsParams", EncryptUtil.encrypt(releaseCouponListParams.toJSONString()));
		return mv;
	}

	@ResponseBody
	@RequestMapping("generalQRCode")
	public Map<String, Object> generalQRCode(Integer custId, Integer shopId, String userCouponEncryptStr, Integer sweepCode) {
		LogUtils.debug(JSONObject.toJSONString(getRequest().getParameterMap()));
		try {
			UserCoupon userCoupon = UserCoupon.toBean(userCouponEncryptStr);
			userCoupon.setSweepCode(sweepCode);
			userCoupon.setValidDate(shopCouponService.getValidDate(userCoupon.getCouponId()));
			userCoupon.setUuid(StringUtils.getRandomWithTimestamp(21));
			// 使用券发放时间
			userCoupon.setCreateTime(new Date());
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("userCouponEncryptStr", userCoupon.toEncryptJSONString());
			jsonObject.put("shopId", shopId);
			String url = Global.getConfig("WX_GET_QRCODE_URL");
			Map<String, Object> params = new HashMap<>();
			params.put("actionUrl", "/userCoupon/page/receiveCouponIndex");
			params.put("jsonStr", jsonObject.toString());
			String wxAccountid = Global.getConfig("KUAIFU_WX_ACCOUNTID");
			String appKey = EncryptUtil.encrypt(wxAccountid);
			params.put("appKey", appKey);
			String urlContent = HttpRequestUtil.httpClientPost(url, params);
			String shortUrl = ShortUrlUtil.shortUrl(urlContent);// https://kuaifu.boshukeji.com/short/{shortUrl}
			String newUrl = Global.getConfig("SJ_SHORT_URL") + "/" + shortUrl;
			ShortUrl t = new ShortUrl();
			t.setShortUrl(shortUrl);
			t.setActionUrl(urlContent);
			shortUrlService.insert(t);
			String qrcodeStream = QrCodeCreateUtil.generalQRCode(newUrl);
			return ResultMapUtil.genDefaultSuccessDataMap(qrcodeStream);
		} catch (Exception e) {
			e.printStackTrace();
			return ResultMapUtil.genErrorMap("新增失败");
		}
	}

	/**
	 * 发放停车券列表
	 *
	 * @param
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("page/releaseCouponListIndex")
	public ModelAndView releaseCouponListIndex(Integer custId, Integer shopId) throws Exception {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("/coupon/releaseCouponList");
		return mv;
	}

	@RequestMapping("page/couponStatisticIndex")
	public ModelAndView couponStatisticIndex(Integer custId, Integer authId) throws Exception {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("/coupon/couponStatistic");

		BmsUser bmsUser = bmsUserService.get(authId);
		mv.addObject("bmsUser", bmsUser);

		ParkingLotCustomer parkingLotCustomer = parkingLotCustomerService.get(custId);
		if (bmsUser.getType() == BmsUserTypeEnum.parking_shop_user.getKey()) {
			parkingLotCustomer.setName(
					parkingLotCustomer.getName() + "·" + parkingShopService.get(bmsUser.getShopId()).getName());
		}
		mv.addObject("parkingLotCustomer", parkingLotCustomer);

		JSONObject parkingLotCouponsParams = new JSONObject();
		parkingLotCouponsParams.put("uri", "/coupon/page/parkingLotCouponsIndex");
		parkingLotCouponsParams.put("custId", custId);
		mv.addObject("parkingLotCouponsParams", EncryptUtil.encrypt(parkingLotCouponsParams.toJSONString()));

		JSONObject couponStatisticParams = new JSONObject();
		couponStatisticParams.put("uri", "/coupon/couponStatistic");
		couponStatisticParams.put("custId", custId);
		mv.addObject("couponStatisticParams", EncryptUtil.encrypt(couponStatisticParams.toJSONString()));

		Date beginDate = DateUtils.setHours(DateUtils.setMinutes(DateUtils.setSeconds(new Date(), 0), 0), 0);
		List<UserCouponReleaseRespVo> vo = shopCouponService.getDailyTotal(bmsUser.getShopId(), bmsUser.getType(), custId,
				beginDate, DateUtils.addDays(beginDate, 1));
		mv.addObject("vo", vo);

		return mv;
	}

	@ResponseBody
	@RequestMapping("couponStatistic")
	public Map<String, Object> couponStatistic(Integer custId, String date, Integer authId) {
		LogUtils.debug(JSONObject.toJSONString(getRequest().getParameterMap()));
		BmsUser bmsUser = bmsUserService.get(authId);
		try {
			Date beginDate = new Date();
			if (!StringUtils.isBank(date)) {
				beginDate = DateTimeUtil.string2Date(date, "yyyy-MM-dd");
			} else {
				beginDate = DateTimeUtil.string2Date(DateTimeUtil.date2String(new Date()), "yyyy-MM-dd 00:00:00");
			}
			List<UserCouponReleaseRespVo> vo = shopCouponService.getDailyTotal(bmsUser.getShopId(), bmsUser.getType(), custId,
					beginDate, DateUtils.addDays(beginDate, 1));
			return ResultMapUtil.genDefaultSuccessDataMap(vo);
		} catch (Exception e) {
			e.printStackTrace();
			return ResultMapUtil.genErrorMap("新增失败");
		}
	}

	@RequestMapping("page/parkingLotCouponsIndex")
	public ModelAndView parkingLotCouponsIndex(Integer custId, String date, Integer authId) throws Exception {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("/coupon/parkingLotCoupons");

		BmsUser bmsUser = bmsUserService.get(authId);
		mv.addObject("bmsUser", bmsUser);

		Date beginDate = new Date();
		if (!StringUtils.isBank(date)) {
			beginDate = DateTimeUtil.string2Date(date, "yyyy-MM-dd");
		} else {
			beginDate = DateTimeUtil.string2Date(DateTimeUtil.date2String(new Date(), "yyyy-MM-dd") + " 00:00:00");
		}
		mv.addObject("date", DateTimeUtil.date2String(beginDate, "yyyy-MM-dd"));
		if (bmsUser.getType() == BmsUserTypeEnum.parking_lot_user.getKey()) {
			List<UserCouponReleaseRespVo> voList = shopCouponService.getDailyReleases(custId, beginDate,
					DateUtils.addDays(beginDate, 1), bmsUser);
			mv.addObject("voList", voList);
		} else {
			List<UserCouponRecordRespVo> voShop = shopCouponService.getShopReleases(custId, beginDate,
					DateUtils.addDays(beginDate, 1), bmsUser);
			mv.addObject("voShop", voShop);
		}

		JSONObject parkingLotCouponsParams = new JSONObject();
		parkingLotCouponsParams.put("uri", "/coupon/parkingLotCoupons");
		parkingLotCouponsParams.put("custId", custId);
		mv.addObject("parkingLotCouponsParams", EncryptUtil.encrypt(parkingLotCouponsParams.toJSONString()));
		return mv;
	}

	@ResponseBody
	@RequestMapping("parkingLotCoupons")
	public Map<String, Object> parkingLotCoupons(Integer custId, String date, Integer page, Integer authId)
			throws Exception {
		if (page == null || page == 0) {
			page = 1;
		}
		Map<String, Object> resultMap = new HashMap<>();
		BmsUser bmsUser = bmsUserService.get(authId);

		Date beginDate = new Date();
		if (!StringUtils.isBank(date)) {
			beginDate = DateTimeUtil.string2Date(date, "yyyy-MM-dd");
		} else {
			beginDate = DateTimeUtil.string2Date(DateTimeUtil.date2String(new Date(), "yyyy-MM-dd") + " 00:00:00");
		}
		try {
			if (bmsUser.getType() == BmsUserTypeEnum.parking_lot_user.getKey()) {
				List<UserCouponReleaseRespVo> voList = shopCouponService.getDailyReleases(custId, beginDate,
						DateUtils.addDays(beginDate, 1), bmsUser);
				resultMap.put("voList", voList);
			} else {
				List<UserCouponRecordRespVo> voShop = shopCouponService.getShopReleases(custId, beginDate,
						DateUtils.addDays(beginDate, 1), bmsUser);
				resultMap.put("voShop", voShop);
			}
			return resultMap;
		} catch (Exception e) {
			e.printStackTrace();
			return ResultMapUtil.genErrorMap("查询失败");
		}
	}

}
